﻿using System;
using System.Buffers.Binary;

namespace WholeSlideImageLibrary.Formats.OptimizedPyramidTiledImage
{
    internal static class FileHeader
    {
        internal static ReadOnlySpan<byte> Identifier => new byte[] { (byte)'O', (byte)'P', (byte)'T', (byte)'I' };
        internal static ReadOnlySpan<byte> Version => new byte[] { (byte)'0', (byte)'1' };

        public static bool TryFindMainBlock(ReadOnlySpan<byte> buffer, long totalFileSize, out long mainBlockPointer)
        {
            if (buffer.Length < 16)
            {
                goto Failure;
            }

            if (!buffer.Slice(0, 4).SequenceEqual(Identifier))
            {
                goto Failure;
            }
            if (!buffer.Slice(4, 2).SequenceEqual(Version))
            {
                goto Failure;
            }
            ushort flags = BinaryPrimitives.ReadUInt16LittleEndian(buffer.Slice(6, 2));
            if (flags != 0)
            {
                goto Failure;
            }
            long pointer = BinaryPrimitives.ReadInt64LittleEndian(buffer.Slice(8));
            if (pointer < 0)
            {
                pointer += totalFileSize;
            }
            mainBlockPointer = pointer;
            return true;

        Failure:
            mainBlockPointer = 0;
            return false;
        }
    }
}
